package com.my.study.io.properties;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @author: yidujun
 * @create: 2021/07/02 16:44
 */
@Slf4j(topic = "c.PropertiesUtil")
public class PropertiesDelegator {

    private String path;
    private Properties properties;

    public PropertiesDelegator(String path) {
        this.path = path;
        properties = new Properties();
        initProperties();
    }

    private void initProperties() {
        try {
            properties.load(FileUtil.getInputStream(path));
        } catch (IOException e) {
            log.error("init [path: {}] properties error.", path);
        }
    }

    public String get(String key) {
        return properties.getProperty(key);
    }

    public void update(String key, String value) {
        properties.setProperty(key, value);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(FileUtil.getAbsolutePath(path));
            //将Properties中的属性列表（键和元素对）写入输出流
            properties.store(fos, "");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(fos);
        }
    }
}
